<template>
 <div class="header">
  <h2 @click="random">推荐产品</h2>
  <h3>实时更新</h3>
 </div>
  <div class="layout2">
    <div class="tuijian">
      <ul>
        <li class="tab" v-for="item in sortedArray" :key="item.id" @click="order(item)">
          <p><img :src="item.ima" alt=""></p>
          <p>{{ item.tea }}</p>
          <p>受欢迎程度：{{ item.rating }}</p>
          <p>{{ item.money }}元</p>
        </li>
      </ul>
    </div>
    <!-- 购物车列表 -->
    <div class="cart-list">
      <li class="buycar" v-for="item in store.state.buycar.filter((item)=>item.num>0)">
        <p class="order">
        <div class="or">
          <p>{{ item.tea }}</p>
          <div style="display: flex;">
            <p>数量:{{ item.num || 1 }}</p>
            &nbsp;
            <p>
              <el-button @click="jia(item.id)">+</el-button>
              <el-button @click="jian(item.id)">-</el-button>
            </p>
          </div>

          <p>{{ item.num * item.money }}元</p>
        </div>
        </p>

      </li>
      <p>总数{{ totalNum }}</p>
      <p>总价：{{ totalPrice }}</p>
      <p @click="addData">立即支付</p>
      <p @click="clearAllCart">清空购物车</p>
    </div>

  </div>
</template>
<script setup>
import store from '../store/index';
import axios from 'axios';
import { computed, onMounted, ref, reactive } from 'vue';
import router from '@/router';
import $api from '@/api';
import { ElMessage } from 'element-plus';


const userHistory = ref([])
const newU = ref([])
const obj = ref({})
//总价
const totalmoney = ref()
// 单价数量
const or = ref(1)
const total = ref()
const money = ref()
const randomItem = ref({})
//推荐算法的实现
const sortedArray = computed(() => {
  //统计历史账单的商品的次数
  const count = {};
  for (let i = 0; i < userHistory.value.length; i++) {
    const ordertea = userHistory.value[i].ordertea;
    if (count[ordertea]) {
      count[ordertea]++;
    } else {
      count[ordertea] = 1;
    }
  }
  //排序
  userHistory.value.sort((a, b) => {
    const aCount = count[a.ordertea];
    const bCount = count[b.ordertea];
    if (aCount > bCount) {
      return -1;
    } else if (aCount < bCount) {
      return 1;
    } else {
      return 0;
    }
  })
  //去重
  newU.value = userHistory.value.reduce((curr, next) => {
    /*判断对象中是否已经有该属性  没有的话 push 到 curr数组*/
    obj.value[next.orderid + next.ordertea] ? '' : obj.value[next.orderid + next.ordertea] = curr.push(next);
    return curr;
  }, [])
  //选出前十受欢迎的商品
  return newU.value.splice(0, 10)
  console.log("推荐商品", newU.value.splice(0, 10));

});

const getData = async () => {
  // const kw = this.search ? `/?id=${this.search}` : "";
  const res = await axios.get("http://localhost:3030/order?$limit=100");
  const { status, data } = res;
  if (status === 200) {
    console.log("data.data", data.data);
    return userHistory.value = data.data

  }
  return ElMessage.error("抓取不到信息...");
};
const addData = async () => {
  store.state.buycar.forEach(async (item) => {
    const res = await $api.post(
      "http://localhost:3030/order?$limit=50",
      {
        orderid: item.id,
        ima: item.imag,
        tea: item.tea,
        money: item.money,
        ordernum: item.num,
        rating: item.rating,
        totalNum:totalNum.value,
        totalPrice:totalPrice.value,
      },

    );
    const { status } = res;
    if (status === 201){
      store.state.buycar=[]
      return ElMessage.success("添加成功");
    } 
  })

}
//随机选择
const random = (arr) => {
  const randomIndex = Math.floor(Math.random() * this.userHistory.length);
  this.randomItem = this.userHistory[randomIndex];
  return this.randomItem;

};

// 添加购物车
const order = (item) => {
  console.log("item", item);
  const { id } = item;
  let record = store.state.buycar.find((n) => n.id == id);
  if (record && record.num) {
    record.num++;
  } else {
    store.state.buycar.push({
      ...item,
      num: 1,
    });
  }
};

// 计算总价 和 总数量
const totalPrice = computed(() => {
  let total = 0;
  store.state.buycar.forEach(({ money, num }) => {

    total += money * num;
  })
  return total;
});
// 计算总数量
const totalNum = computed(() => {
  let total = 0;
  store.state.buycar.forEach(({ num }) => {
    total += num;
  });
  return total;
});
// 清空购物车
const clearAllCart = () => {
  store.state.buycar = [];
};

const jia = (id) => {
  store.state.buycar.forEach(t => {
    if (t.id == id) {
      if (!t.num) {
        t.num = 2
        or.value = t.num
      } else {
        t.num++
        or.value = t.num
        totalmoney.value = or.value * t.money

      }
    }
  })
}
const jian = (id) => {
  store.state.buycar.forEach(t => {
    console.log("t.money", t.money);
    if (t.id == id) {
      if (!t.num || t.num == 0) {
        const index = store.state.buycar.findIndex(t => t.id === id)
        // 如果找到了该商品，则从数组中删除该商品
        store.state.buycar.splice(index, 1);

      }
      // store.state.buycar = []
      if (t.num > 0) {
        t.num--
        or.value = t.num
      }
    }
  })
}

onMounted(getData)




</script>

<style lang="scss">
.header {
  height: 100px;
  font-size: 24px;  
  background-color: #f5f5dc;
}
.layout2 {
  display:flex ;
  width: 100%;
  height: 100%;
  background-color: rgb(245, 245, 220);
  
}

ul {
  width: 1360px;
  justify-content: space-around;
  display: flex;
  flex-grow: 1;
  flex-wrap: wrap;
  align-content: center;
  border-top: 1px solid #000;

}

img {
  width: 100px;
  height: 100px;
}
.cart-list {
  width: 400px;
  font-size: 18px;

  background-color: #748d79;
  border-radius: 15px;
}
p.order {
  .or {
    display: flex;
    justify-content: space-around;
  }
}
.tab {
  width: 420px;
  text-align: center;
  margin-top: 4px;

}
</style>